package net.sx.minemodule.mvp.activities;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.util.ToastUtil;

import net.sx.minemodule.R;
import net.sx.minemodule.databinding.MineActivityAfterRefundDetailBinding;
import net.sx.minemodule.mvp.bean.EnumRefundType;
import net.sx.minemodule.mvp.bean.EnumSchedule;
import net.sx.minemodule.mvp.bean.RefundBean;
import net.sx.minemodule.mvp.bean.RefundGoodsBean;
import net.sx.minemodule.mvp.item.RefundDetailGoodsItem;
import net.sx.minemodule.mvp.presenters.MineAfterRefundDetailPresenter;
import net.sx.minemodule.mvp.views.MineAfterRefundDetailView;
import net.sx.minemodule.widget.RefundActionsView;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 退款/售后 详情页  1000013
 *
 * @author 冯鑫林 2019-7-4 14:26
 * update 20190724 long.tu
 */
@Route(path = ARouterPath.PATH_MINE_AFTER_DETAIL)
public class MineAfterRefundDetailActivity
        extends MyBaseFragmentActivity<MineActivityAfterRefundDetailBinding, MineAfterRefundDetailPresenter>
        implements MineAfterRefundDetailView {
    @Autowired
    public String AfterBean;
    private RefundBean refundDetailData;
    private MultiTypeAdapter goodsAdapter;

    @Override
    protected MineAfterRefundDetailPresenter getPresenter() {
        return new MineAfterRefundDetailPresenter(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.mine_activity_after_refund_detail;
    }

    @Override
    protected void initEvent() {
        ARouter.getInstance().inject(this);
        refundDetailData = JSON.parseObject(AfterBean, RefundBean.class);
        mBinding.setViewmodel(this);
        mBinding.invalidateAll();
        mBinding.mineRvRefundDetailGoods.setLayoutManager(new LinearLayoutManager(this));
        goodsAdapter = new MultiTypeAdapter();
        mBinding.mineRvRefundDetailGoods.setAdapter(goodsAdapter);
        //initData();
        getPresenter().initData(refundDetailData.getId());
//        getPresenter().initData(27);
    }

    private void initData() {
        goodsAdapter.clear();
        //20190723 接口改动，一个售后订单只有一个商品
        RefundGoodsBean bean = refundDetailData.getOrderReturnApplyItemResult();
        RefundDetailGoodsItem item = bean.createItem(goodsAdapter);
        goodsAdapter.addItem(item);
        goodsAdapter.notifyDataSetChanged();
//        20190723 接口未返回，暂时隐藏
//        String expirationTime = refundDetailData.getExpirationTime();
//        if (!TextUtils.isEmpty(expirationTime)) {
//            //2019-07-08T08:01:34.571+0000
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.SIMPLIFIED_CHINESE);
//            try {
//                Date parse = simpleDateFormat.parse(expirationTime);
//                getPresenter().startCountDown(parse, refundDetailData.getId());
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        } else {
//            mBinding.mineTvRefundDetailTime.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);
        setTitle(getString(R.string.mine_refund_detail));
    }

    /**
     * 当前 售后/退款状态，枚举获取
     * 退款: 等待卖家处理-（已撤销申请）-商家审核完成
     * 退款退货：等待卖家处理-已退货，等待卖家收货-等待卖家验货-等待退款中-退款退货成功 (申请驳回)(已撤销申请)
     *
     * @return
     */
    public String refundStatus() {
        return EnumSchedule.getScheduleName(refundDetailData.getStatus(), refundDetailData.getStatus());
    }

    /**
     * 当前 售后/退 倒计时可见性
     * 20190723 接口未返回，暂时隐藏
     *
     * @return
     */
    public int timevisible() {
        return View.GONE;
    }

    /**
     * 水平进度右边显示的当前进度： "退款：已申请退款"……
     *
     * @return
     */
    public String currentStatus() {
        String type = EnumRefundType.getRefundTypeName(refundDetailData.getReturnType());
        String status = EnumSchedule.getScheduleName(refundDetailData.getStatus(), refundDetailData.getReturnType());
        return type + "：" + status;
    }

    /**
     * 进度
     * 水平进度data:退款(3个)；退款退货(4个)
     *
     * @return
     */
    public List<EnumSchedule> stepData() {
        return getPresenter().getStepData(refundDetailData.getReturnType());
    }

    /**
     * 进度完成到哪一步了
     *
     * @return
     */
    public int status() {
        return refundDetailData.getStatus();
    }

    /**
     * 订单编号
     *
     * @return
     */
    public String orderNum() {
        return getString(R.string.mine_order_number) + "：" + refundDetailData.getOrderSn();
    }

    /**
     * 售后编号
     *
     * @return
     */
    public String afterOrderNum() {
        return getString(R.string.mine_after_order_number) + "：" + refundDetailData.getReturnApplySn();
    }

    public String refundReason() {
        //只显示原因
        return EnumRefundType.getRefundTypeName(refundDetailData.getReturnType()) + "原因：" + refundDetailData.getNote();
    }

    /**
     * 退款金额
     */
    public String refundAmount() {
        return getString(R.string.mine_refund_amount) + "：￥" + refundDetailData.getReturnAmount().toString();
    }

    /**
     * 反还积分
     */
    public String refundScore() {
        int point = 0;
        if (refundDetailData.getOrderReturnApplyItemResult() != null) {
            point = refundDetailData.getOrderReturnApplyItemResult().getPoint();
        }
        return getString(R.string.mine_refund_score) + "：" + point;
    }

    /**
     * 反还佣金
     */
    public String refundCommission() {
        BigDecimal Commission = new BigDecimal(0);
        if (refundDetailData.getOrderReturnApplyItemResult() != null) {
            Commission = refundDetailData.getOrderReturnApplyItemResult().getCommission();
        }
        return getString(R.string.mine_refund_commission) + "：" + Commission.toString();
    }

    /**
     * 申请数量
     */
    public String applyNumber() {
        int num = 1;
        if (refundDetailData.getOrderReturnApplyItemResult() != null) {
            num = refundDetailData.getOrderReturnApplyItemResult().getNum();
        }
        return getString(R.string.mine_apply_number) + "：" + num;
    }

    /**
     * 申请时间
     */
    public String applyTime() {
        return getString(R.string.mine_apply_time) + "：" + refundDetailData.getCreateTime();
    }

    /**
     * 物流单号
     */
    public String logisticsNumber() {
        return getString(R.string.mine_logistics_number) + "：" + refundDetailData.getLogisticsCompany()
                + " " + refundDetailData.getLogisticsSn();
    }

    /**
     * 物流单号显示状态
     */
    public int logisticsNumberVisible() {
        if (refundDetailData.getReturnType() == EnumRefundType.REFUND_GOODS.getKey()
                || refundDetailData.getReturnType() == EnumRefundType.CHANGE_GOODS.getKey()) {
            if (refundDetailData.getStatus() > EnumSchedule.RETURN_GOODS_WAIT_RECEIVE.getKey()
                    && refundDetailData.getStatus() != EnumSchedule.WAITING_REQUEST_10.getKey()
                    && refundDetailData.getStatus() != EnumSchedule.WAITING_REQUEST_11.getKey()) {
                return View.VISIBLE;
            }
        }
        return View.GONE;
    }

    /**
     * 是否显示填写物流单号
     *
     * @return 只有待买家退货状态才显示
     */
    public int canInputLogistics() {
        return refundDetailData.getReturnType() == EnumRefundType.REFUND_GOODS.getKey()
                && refundDetailData.getStatus() == EnumSchedule.RETURN_GOODS_WAIT_RECEIVE.getKey() ? View.VISIBLE : View.GONE;
    }

    /**
     * 是否显示填写物流单号(水平进度view控制显示)
     *
     * @return 只有待买家退货状态才显示
     */
    public int notCanInputLogistics() {
        return refundDetailData.getReturnType() == EnumRefundType.REFUND_GOODS.getKey()
                && refundDetailData.getStatus() == EnumSchedule.RETURN_GOODS_WAIT_RECEIVE.getKey() ? View.GONE : View.VISIBLE;
    }


    /**
     * 回寄地址，姓名，电话
     *
     * @return
     */
    public String refundGoodsAddressName() {
        return refundDetailData.getContactsUserName() + " " + refundDetailData.getContactsPhone();
    }

    /**
     * 回寄地址
     *
     * @return
     */
    public String refundGoodsAddress() {
        return refundDetailData.getRegister_address();
    }

    /**
     * 填写快递单号，点击
     */
    public void onInputLogisticsClick(View v) {
        startActivityForResult(new Intent(this, MineRefundInputLogisticsActivity.class)
                .putExtra("refundBean", refundDetailData), 10086);
    }

    /**
     * 底部的一堆按钮，一般根据状态不同而不同
     * 1. 物流查看后端未实现
     */
    public List<RefundActionsView.RefundDetailAction> bottomActions() {
        List<RefundActionsView.RefundDetailAction> result = new ArrayList<>();
        result.add(new RefundActionsView.RefundDetailAction("联系客服", v -> {
            contentServicer();
        }));
        int status = refundDetailData.getStatus();
        int type = refundDetailData.getReturnType();
        EnumSchedule enumSchedule = EnumSchedule.getSchedule(status, type);
        //
        if (enumSchedule == EnumSchedule.WAITING_REQUEST_10 || enumSchedule == EnumSchedule.WAITING_REQUEST_11) {
            //卖家审核前
            result.add(new RefundActionsView.RefundDetailAction("撤销申请", v -> {
                new CancelDialog(MineAfterRefundDetailActivity.this).show();
            }));
        }
        //WAITING_REQUEST_10 WAITING_REQUEST_11 可修改
        if (refundDetailData.isDelete() || EnumSchedule.WAITING_REQUEST_10.getKey() == status || EnumSchedule.WAITING_REQUEST_11.getKey() == status) {
            //撤销后可以重新修改
            result.add(new RefundActionsView.RefundDetailAction("重新修改", v -> {
                //跳转申请售后页面，带一个售后id过去
                ARouter.getInstance().build(ARouterPath.PATH_MINE_ORDER_AFTER_SALES_REQUEST).withInt("returnTypeId", refundDetailData.getId()).
                        navigation();
            }));
        }
        //填过物流信息就显示查看物流
        if (type == EnumRefundType.REFUND_GOODS.getKey()
                && (status > EnumSchedule.RETURN_GOODS_WAIT_RECEIVE.getKey()
                && status != EnumSchedule.WAITING_REQUEST_10.getKey()
                && status != EnumSchedule.WAITING_REQUEST_11.getKey()
        )) {
            //退款退货，换货,且状态在已发货之后
//            result.add(new RefundActionsView.RefundDetailAction("查看物流", v -> {
//                ToastUtil.showToast("查看物流，应该是跳转到查看物流页面");
//            }));
        }
        return result;
    }

    /**
     * 退款  退款退货，换货
     * {@link EnumRefundType}
     */
    public int refundType() {
        return refundDetailData.getReturnType();
    }

    /**
     * 是否撤回申请
     *
     * @return
     */
    public boolean isDelete() {
        return refundDetailData.isDelete();
    }

    /**
     * 联系客服
     * todo 未告知客服电话号码
     */
    private void contentServicer() {
        Uri uri = Uri.parse("tel:18788888888");
        Intent it = new Intent(Intent.ACTION_DIAL, uri);
        startActivity(it);
    }

    @Override
    public void loadDataSuccess(RefundBean detailBean) {
        hideLoad();
        refundDetailData = detailBean;
        mBinding.invalidateAll();
        initData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086 && resultCode == RESULT_OK) {
            //填写单号完成，状态需要更新
            getPresenter().initData(refundDetailData.getId());
        }
    }

    @Override
    public void loadDataFail(String message) {
        hideLoad();
        ToastUtil.showToast(message);
    }

    @Override
    public void cancelSuccess() {
        hideLoad();
        finish();
    }

    @Override
    public void cancelFail(String message) {
        hideLoad();
        ToastUtil.showToast(message);
    }

    @Override
    public void onTimeTick(String timeCountDown) {
        mBinding.mineTvRefundDetailTime.setText(timeCountDown);
    }

    class CancelDialog extends Dialog {

        public CancelDialog(Context context) {
            super(context);
            setCancelable(true);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mine_refund_cancel_dialog);
            findViewById(R.id.tv_refund_cancel_cancel).setOnClickListener(v -> dismiss());
            findViewById(R.id.tv_refund_cancel_sure).setOnClickListener(v -> {
                dismiss();
                showLoad("提交中...");
                mPresenter.cancelRefundOrder("" + refundDetailData.getId());
            });
        }
    }
}
